package cn.juforg.gobang;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import cn.juforg.gobang.interfaces.ChessBoardDao;
import cn.juforg.gobang.interfaces.impl.ChessBoardImpl;
import cn.juforg.gobang.player.HumanPlayer;
/**
 * 
 * @author Juforg
 * 棋盘类
 */
public class ChessBoard extends View{

	
	//游戏状态常量
	public static final char READY = '1';				//等待开始
	public static final char RUNNING = '2';				//正在游戏中
	public static final char PLAYER_ONE_LOST = '3';		//玩家一输了
	public static final char PLAYER_TWO_LOST = '4';		//玩家二输了
	public static final boolean PLAYER1FLAG = true;
	public static final boolean PLAYER2FLAG = false;
	
	public static final char BLACK = '0';
	public static final char NEW_BLACK = '2';			//黑色棋子
	public static final char WHITE = '1';					
	public static final char NEW_WHITE = '3';			//白色棋子

	public static int chessSize = 32;					//棋子大小
	
	private static char currentStatus = RUNNING;			//当前状态（默认为等待开始）

	public static int maxX;							//屏幕的最大坐标（即右下角点的坐标）
	public static int maxY;
	
	public static int xOffset;							//第一点偏离左上角从像数，为了棋盘居中
	public static int yOffset;
	
	private List<Line> lines = new ArrayList<Line>();	//棋盘上所有的线
//	private List<Chess> chesses = new ArrayList<Chess>();//棋盘上所有的棋子
	public static char[][] chessArray;						 //棋盘上所有的点
	
	private BasePlayer player1 = new HumanPlayer(true);	//玩家一(默认为人类玩家）
	private BasePlayer player2 ;						//玩家二
//	private BasePlayer currentTrun = player1;			//当前玩家 默认玩家1先
	private boolean currentPlayer = PLAYER1FLAG;		//true为玩家1 false为玩家2
	
	private Paint paint = new Paint();					//画笔对象
	
	private Bitmap[] chessColorArray = new Bitmap[4];		//不同颜色的Bigmap数组
	
	public static Chess player1newchs = null;				//玩家前次下的棋子
	public static Chess player2newchs = null;

	public static ChessBoardDao chssboddao = new ChessBoardImpl();//棋盘接口
	private Activity aty;
	private RefreshHandler computerRun =  new RefreshHandler();
	private int delayMillis = 400 ;
	
	

	public ChessBoard(Context context, AttributeSet attrs) {
		super(context, attrs);
		setFocusable(true);
		Resources r = this.getContext().getResources();
		chssboddao.fillChessArrays(chessColorArray, Character.getNumericValue(BLACK), r.getDrawable(R.drawable.black_chess), chessSize);
		chssboddao.fillChessArrays(chessColorArray, Character.getNumericValue(NEW_BLACK), r.getDrawable(R.drawable.new_black_chess), chessSize);
		chssboddao.fillChessArrays(chessColorArray, Character.getNumericValue(WHITE), r.getDrawable(R.drawable.white_chess), chessSize);
		chssboddao.fillChessArrays(chessColorArray, Character.getNumericValue(NEW_WHITE), r.getDrawable(R.drawable.new_white_chess), chessSize);
		
		//设置画线时用的颜色
        paint.setColor(Color.LTGRAY);
       
	}
	
	/*
	 * 初始横线和竖线的数目
	 * @see android.view.View#onSizeChanged(int, int, int, int)
	 */
	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		maxX = (int) Math.floor(w / chessSize);
		maxY = (int) Math.floor(h / chessSize);
        BaseAI.CalculateRange.xstart = maxX;
        BaseAI.CalculateRange.ystart = maxY;
		//设置X、Y座标微调值，目的整个框居中
		 xOffset = ((w - (chessSize * maxX)) / 2);
	     yOffset = ((h - (chessSize * maxY)) / 2);
	   //创建棋盘上的线条
	     this.createLines();
	   //初始化棋盘上所有空白点
	     chessArray = new char[ChessBoard.maxX][ChessBoard.maxY];
	     BaseAI.weights = new int[ChessBoard.maxX][ChessBoard.maxY];
	     BaseAI.weights[0][0]=-1;
	     for (int i = 0; i < maxX; i++) {
			for (int j = 0; j < maxY; j++) {
				chessArray[i][j] = '4';
			}
		}
	}
	
	//计算棋盘上所有的线
    private void createLines(){
    	for (int i = 0; i <= maxX; i++) {//竖线
    		lines.add(new Line(xOffset+i*chessSize-chessSize/2, yOffset, xOffset+i*chessSize-chessSize/2, yOffset+maxY*chessSize));
		}
    	for (int i = 0; i <= maxY; i++) {//横线
    		lines.add(new Line(xOffset, yOffset+i*chessSize-chessSize/2, xOffset+maxX*chessSize, yOffset+i*chessSize-chessSize/2));
		}
    }

	
	//处理触摸事件
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		//还没有开局，或者是按下事件，不处理，只处理开局后的触摸弹起事件
		if(!chssboddao.isRunning(currentStatus) || event.getAction()!=MotionEvent.ACTION_UP){
			Log.i("motion", "event.getAction()="+event.getAction());
			System.out.println("还没开局！");
			return true;
		}
		//是否轮到我下
		if(chssboddao.isMyTurn(player1, currentPlayer)){
//			chssboddao.playerRun(player1, event); 
			chssboddao.playerRun(player1, event, this);
			chssboddao.refressCanvas(this);
			if (BaseAI.class.isAssignableFrom(player2.getClass()) && chssboddao.isMyTurn(player2, currentPlayer) && PLAYER_TWO_LOST != ChessBoard.currentStatus) {
				System.out.println("玩家2是AI");
				computerRun.computerRunAfter(delayMillis);
//				chssboddao.playerRun(player2, player2.run(), this);
			}
			return false;
		}else if (chssboddao.isMyTurn(player2, currentPlayer) && !BaseAI.class.isAssignableFrom(player2.getClass())) {
			chssboddao.playerRun(player2, event, this);
			return false;
		}
		return true;
	}
	

   
	class RefreshHandler extends Handler {

		//这个方法主要在指定的时刻发一个消息
        public void computerRunAfter(long delayMillis) {
        	this.removeMessages(0);
        	//发消息触发handleMessage函数
            sendMessageDelayed(obtainMessage(0), delayMillis);
        }
        
        //收到消息
        @Override
        public void handleMessage(Message msg) {
        	//电脑走一步棋子
        	chssboddao.playerRun(player2, player2.run(), ChessBoard.this);
    		//刷新一下
        	chssboddao.refressCanvas(ChessBoard.this);
        }
    };
    
    @Override
    protected void onDraw(Canvas canvas) {
    	chssboddao.drawChssboardLines(lines, canvas, paint);
    	chssboddao.drawChess(canvas, chessArray, chessColorArray,paint);
    }
    
	public static int getMaxX() {
		return maxX;
	}

	public static int getMaxY() {
		return maxY;
	}

	public static int getxOffset() {
		return xOffset;
	}

	public static int getyOffset() {
		return yOffset;
	}
	public static int getChessSize() {
		return chessSize;
	}
	
	public static char getCurrentStatus() {
		return currentStatus;
	}

	public static void setCurrentStatus(char currentStatus) {
		ChessBoard.currentStatus = currentStatus;
	}


	public boolean getCurrentPlayer() {
		return currentPlayer;
	}

	public void setCurrentPlayer(boolean currentPlayer) {
		this.currentPlayer = currentPlayer;
	}
	public void setChessArray(char[][] chessArray) {
		ChessBoard.chessArray = chessArray;
	}
	public char[][] getChessArray() {
		return chessArray;
	}

	public static Chess getPlayer1newchs() {
		return player1newchs;
	}

	public static void setPlayer1newchs(Chess player1newchs) {
		ChessBoard.player1newchs = player1newchs;
	}

	public static Chess getPlayer2newchs() {
		return player2newchs;
	}

	public static void setPlayer2newchs(Chess player2newchs) {
		ChessBoard.player2newchs = player2newchs;
	}

	public void setPlayer2(BasePlayer player2) {
		this.player2 = player2;
	}

	public Activity getAty() {
		return aty;
	}

	public void setAty(Activity aty) {
		this.aty = aty;
	}


}
